package com.gdwp;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

public class StsOssExample {
    public static void main(String[] args) {
        // 1. 创建STS客户端
        DefaultProfile profile = DefaultProfile.getProfile(
            "cn-shanghai",          // 区域ID
            "LTAI5t7n1RCrmdYdnTAi4NhN",   // RAM用户AccessKey
            "v1rN1k7m2v5LX1LM11CdVRzFFTMZ5A" // RAM用户AccessKeySecret
        );
//        {
//            "access_key_id":"LTAI5t7n1RCrmdYdnTAi4NhN",
//                "access_key_secret":"v1rN1k7m2v5LX1LM11CdVRzFFTMZ5A",
//                "region":"oss-cn-shanghai",
//                "bucket":"qy-uav",
//                "arn":"acs:ram::1504073582788611:role/aliyunserviceroleforresourcemetacenter",
//                "policy": "",
//                "role_session_name":"AliyunServiceRoleForResourceMetaCenter",
//                "provider":"ali"
//        }

        IAcsClient client = new DefaultAcsClient(profile);

        // 2. 创建AssumeRole请求
        AssumeRoleRequest request = new AssumeRoleRequest();
        request.setRoleArn("acs:ram::1504073582788611:role/aliyunserviceroleforresourcemetacenter"); // 角色ARN
        request.setRoleSessionName("session-name"); // 会话名称
        request.setDurationSeconds(3600L); // 设置凭证有效期^7^

        try {
            // 3. 获取临时凭证
            AssumeRoleResponse response = client.getAcsResponse(request);
            String accessKeyId = response.getCredentials().getAccessKeyId();
            String accessKeySecret = response.getCredentials().getAccessKeySecret();
            String securityToken = response.getCredentials().getSecurityToken();

            // 4. 使用临时凭证初始化OSS客户端
            OSS ossClient = new OSSClientBuilder().build(
                "https://oss-cn-shanghai.aliyuncs.com", // Endpoint
                accessKeyId,
                accessKeySecret,
                securityToken
            );

            // 5. 执行OSS操作（示例：列出Bucket中的文件）
            ossClient.listObjects("qy-uav").getObjectSummaries()
                .forEach(obj -> System.out.println(obj.getKey()));

            // 6. 关闭客户端
            ossClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
